import 'dart:convert';

import '../../index.dart';

typedef FilterCallback = void Function(List<FilterSelectData> selectList);

enum FilterWidgetStyle { defaultStyle /* 0 */, roundStyle }

class FilterWidget extends StatefulWidget {
  FilterCallback onSelect;
  FilterCallback? onInit;
  FilterWidgetStyle style;

  String? initConfigJson;
  List<FilterItemData>? initConfig;

  FilterWidget(
      {Key? key,
      this.initConfigJson,
      this.initConfig,
      required this.onSelect,
      this.onInit,
      this.style = FilterWidgetStyle.defaultStyle})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => _FilterWidgetState();
}

class _FilterWidgetState extends State<FilterWidget> {
  final GlobalKey globalKey = GlobalKey();
  List<FilterItemData>? itemList;
  int clickTimeMillis = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 解析初始化配置
    if (widget.initConfig == null) {
      // if (widget.initConfigJson != null) {
      //   var config = jsonDecode(widget.initConfigJson!);
      //   if (List == config.runtimeType) {
      //     itemList =
      //         (config as List).map((e) => FilterItemData.fromJson(e)).toList();
      //   }
      // }
      itemList = FilterUtils.jsonToFilterList(widget.initConfigJson);
    } else {
      itemList = widget.initConfig;
    }
    if (widget.onInit != null) {
      //初始化完成后 调用一次 返回最新的选中内容
      _handleSelectData(isInit: true);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      key: globalKey,
      children: [
        const Divider(
          height: 1,
        ),
        SizedBox(height: 50, child: _buildBody()),
        const Divider(
          height: 1,
        )
      ],
    );
  }

  Widget _buildBody() {
    if (itemList != null) {
      List<Widget> btnList = [];

      for (FilterItemData itemData in itemList!) {
        List<Widget> rowList = [];
        rowList.add(Flexible(
            child: Text(itemData.name,
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
                style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                      color: itemData.isSelect()
                          ? Theme.of(context).primaryColor
                          : null,
                    ))));

        switch (itemData.type) {
          case filterItemTypeTwo:
            {
              //上下箭头
              rowList.add(Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  SizedBox(
                    height: 6,
                    child: Icon(
                      Icons.arrow_drop_up,
                      size: 16,
                      color: itemData.select == 1
                          ? Theme.of(context).primaryColor
                          : null,
                    ),
                  ),
                  Icon(
                    Icons.arrow_drop_down,
                    size: 16,
                    color: itemData.select == 2
                        ? Theme.of(context).primaryColor
                        : null,
                  ),
                ],
              ));
            }
            break;
          case filterItemTypeOne:
          case filterItemTypeTime:
            {
              //单箭头
              rowList.add(Icon(
                itemData.isSelect()
                    ? Icons.arrow_drop_up
                    : Icons.arrow_drop_down,
                size: 16,
                color:
                    itemData.isSelect() ? Theme.of(context).primaryColor : null,
              ));
            }
            break;
          case filterItemTypeFilter:
            {
              //筛选
              rowList.add(Icon(
                Icons.filter_alt_outlined,
                size: 16,
                color:
                    itemData.isSelect() ? Theme.of(context).primaryColor : null,
              ));
            }
            break;
        }

        btnList.add(
          Expanded(
            child: InkWell(
              child: SizedBox(
                height: 50,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: rowList,
                ),
              ),
              onTap: () {
                switch (itemData.type) {
                  case filterItemTypeNone:
                    {
                      //没有箭头
                      setState(() {
                        //如果是单选 就不能自己设置为false 多选则可以
                        if (itemData.radio) {
                          //单选
                          if (!itemData.isSelect()) {
                            //未选中 则设置未选中
                            itemData.setSelect(true);
                          } else {
                            //如果是选中状态 不做处理
                            return;
                          }
                        } else {
                          //多选
                          itemData.setSelect(!itemData.isSelect());
                        }
                        //让其它数据保持一致
                        _updateOtherData(itemData);
                      });
                      _handleSelectData();
                    }
                    break;
                  case filterItemTypeTwo:
                    {
                      //两个箭头->支持正反排序
                      if (itemData.radio) {
                        // 单选
                        setState(() {
                          if (!itemData.isSelect()) {
                            //未选中 则改为选中
                            itemData.setSelect(true);
                          } else {
                            //选中状态 修改排序方式
                            itemData.updateSelect();
                          }
                          _updateOtherData(itemData);
                        });
                      } else {
                        // 多选
                        setState(() {
                          //在未选中、倒序、正序中切换
                          itemData.select++;
                          if (itemData.select > 2) {
                            itemData.select = 0;
                          }
                          _updateOtherData(itemData);
                        });
                      }
                      _handleSelectData();
                    }
                    break;
                  case filterItemTypeOne:
                    {
                      if (itemData.children != null) {
                        int currentTimeMillis =
                            DateTime.now().millisecondsSinceEpoch;
                        // 2次点击间隔0.5s 避免动画出现bug
                        if (currentTimeMillis - clickTimeMillis < 500) {
                          return;
                        } else {
                          clickTimeMillis = currentTimeMillis;
                        }
                        setState(() {
                          itemData.setSelect(true);
                        });

                        //传入偏移值
                        //获取position
                        RenderBox? box = globalKey.currentContext
                            ?.findRenderObject() as RenderBox;
                        Offset offset = box.localToGlobal(Offset.zero);
                        //获取size
                        Size size = box.size;

                        Offset offsetLT =
                            Offset(offset.dx, offset.dy + size.height);

                        if (itemData.radio) {
                          // 单选
                          filterPopup(
                              context,
                              FilterRadioPage(
                                  itemData: itemData,
                                  onSelect: (FilterItemData filterItemData) {
                                    //修改其它地方 code相同的内容
                                    setState(() {
                                      //更新itemData
                                      int index = itemList!.indexOf(itemData);
                                      itemData = filterItemData;
                                      itemList!.replaceRange(
                                          index, index + 1, [filterItemData]);
                                      _updateOtherData(filterItemData);
                                    });
                                    _handleSelectData();
                                  },
                                  onDismiss: () {
                                    setState(() {
                                      //修改顶部按钮的选中状态
                                      itemData.setSelect(false);
                                    });
                                  },
                                  offsetLT: offsetLT),
                              offsetLT: offsetLT);
                        } else {
                          //多选
                          filterPopup(
                              context,
                              FilterMultiplePage(
                                  itemData: itemData,
                                  onSelect: (FilterItemData filterItemData) {
                                    setState(() {
                                      //修改其它地方 code相同的内容
                                      //更新itemData
                                      int index = itemList!.indexOf(itemData);
                                      itemData = filterItemData;
                                      itemList!.replaceRange(
                                          index, index + 1, [filterItemData]);
                                      _updateOtherData(filterItemData);
                                    });
                                    _handleSelectData();
                                  },
                                  onDismiss: () {
                                    setState(() {
                                      itemData.setSelect(false);
                                    });
                                  },
                                  offsetLT: offsetLT),
                              offsetLT: offsetLT);
                        }
                      }
                    }
                    break;
                  case filterItemTypeFilter:
                    {
                      if (itemData.children != null) {
                        // 2次点击间隔0.5s 避免动画出现bug
                        int currentTimeMillis =
                            DateTime.now().millisecondsSinceEpoch;
                        if (currentTimeMillis - clickTimeMillis < 500) {
                          return;
                        } else {
                          clickTimeMillis = currentTimeMillis;
                        }

                        setState(() {
                          itemData.setSelect(true);
                        });
                        //设置偏移值
                        Offset offsetLT = const Offset(50, 0);

                        filterPopup(
                            context,
                            FilterRightPage(
                                itemData: itemData,
                                onSelect: (FilterItemData filterItemData) {
                                  setState(() {
                                    //更新itemData
                                    int index = itemList!.indexOf(itemData);
                                    itemData = filterItemData;
                                    itemList!.replaceRange(
                                        index, index + 1, [filterItemData]);
                                    _updateOtherData(filterItemData);
                                  });
                                  _handleSelectData();
                                },
                                onDismiss: () {
                                  setState(() {
                                    itemData.setSelect(false);
                                  });
                                },
                                offsetLT: offsetLT),
                            offsetLT: Offset.zero);
                      }
                    }
                    break;
                  case filterItemTypeTime:
                    {}
                    break;
                  default:
                    break;
                }
              },
            ),
          ),
        );
      }

      return Row(
        children: btnList,
      );
    } else {
      return const Center(
        child: Text(
          "暂无筛选按钮",
          style: TextStyle(fontSize: 14, color: Color(0xFFC9C9C9)),
        ),
      );
    }
  }

  void _updateOtherData(FilterItemData itemData) {
    //保持其它数据与传入数据一致
    switch (itemData.type) {
      //当前数据类型
      case filterItemTypeNone:
      case filterItemTypeTwo:
        {
          //改其它按钮的内容
          _updateSelectData(itemData.radio, itemData, itemData.code,
              itemData.value, itemData.select);
        }
        break;
      case filterItemTypeOne:
        {
          //遍历修改
          for (FilterItemData selectItemData in itemData.children!) {
            if (!itemData.radio ||
                (itemData.radio && selectItemData.isSelect())) {
              //多选 或者 单选选中状态时
              _updateSelectData(itemData.radio, itemData, itemData.code,
                  selectItemData.value, selectItemData.select);
            }
          }
        }
        break;
      case filterItemTypeFilter:
        {
          //遍历修改
          for (FilterItemData filterItemData in itemData.children!) {
            //获取第一层 能取到code
            for (FilterItemData selectItemData in filterItemData.children!) {
              //获取第二层 能取到value
              if (!filterItemData.radio ||
                  (filterItemData.radio && selectItemData.isSelect())) {
                //多选 或者 单选选中状态时
                _updateSelectData(
                    filterItemData.radio,
                    itemData,
                    filterItemData.code,
                    selectItemData.value,
                    selectItemData.select);
              }
            }
          }
        }
        break;
      case filterItemTypeTime:
        {}
        break;
      default:
        break;
    }
  }

  void _updateSelectData(bool radio, FilterItemData itemData, String? code,
      String? value, int select) {
    //单选选中 只会有一项被选中 所以只会调用一次
    for (FilterItemData tempItemData in itemList!) {
      if (itemData != tempItemData) {
        //待修改数据的类型
        switch (tempItemData.type) {
          case filterItemTypeNone:
          case filterItemTypeTwo:
            {
              //如果被修改的是无箭头和双箭头按钮 则需要保持数据的选中值
              if (tempItemData.code == code && radio == tempItemData.radio) {
                if (tempItemData.value == value) {
                  tempItemData.select = select;
                } else if (radio) {
                  tempItemData.setSelect(false);
                }
              }
            }
            break;
          case filterItemTypeOne:
            {
              //如果被修改的是一个箭头 只修改单选数据
              if (tempItemData.code == code &&
                  tempItemData.children != null &&
                  radio == tempItemData.radio) {
                for (FilterItemData childItemData in tempItemData.children!) {
                  if (childItemData.value == value) {
                    childItemData.select = select;
                  } else if (radio) {
                    childItemData.setSelect(false);
                  }
                }
              }
            }
            break;
          case filterItemTypeFilter:
            //遍历修改
            {
              if (tempItemData.children != null) {
                for (FilterItemData filterItemData in tempItemData.children!) {
                  //如果被修改的是一个箭头 只修改单选数据
                  if (filterItemData.code == code &&
                      filterItemData.children != null &&
                      radio == filterItemData.radio) {
                    for (FilterItemData childItemData
                        in filterItemData.children!) {
                      if (childItemData.value == value) {
                        childItemData.select = select;
                      } else if (radio) {
                        childItemData.setSelect(false);
                      }
                    }
                  }
                }
              }
            }
            break;
          case filterItemTypeTime:
            {}
            break;
          default:
            break;
        }
      }
    }
  }

  void _handleSelectData({bool isInit = false}) {
    List<FilterSelectData> selectList = [];

    //第一层
    for (FilterItemData itemData in itemList!) {
      switch (itemData.type) {
        case filterItemTypeNone:
        case filterItemTypeTwo:
          {
            if (itemData.select == 1) {
              //选中第一项
              addValue(selectList, itemData.code, itemData.value);
            } else if (itemData.select == 2) {
              //选中第二项
              addValue(selectList, itemData.code, "【asc】-${itemData.value}");
            }
          }
          break;
        case filterItemTypeOne:
          {
            for (FilterItemData childItemData in itemData.children!) {
              if (childItemData.select == 1) {
                //选中第一项
                addValue(selectList, itemData.code, childItemData.value);
              } else if (childItemData.select == 2) {
                //选中第二项
                addValue(
                    selectList, itemData.code, "【asc】-${childItemData.value}");
              }
            }
          }
          break;
        case filterItemTypeFilter:
          //遍历修改
          {
            for (FilterItemData filterItemData in itemData.children!) {
              //如果被修改的是一个箭头 只修改单选数据
              for (FilterItemData childItemData in filterItemData.children!) {
                if (childItemData.select == 1) {
                  //选中第一项
                  addValue(
                      selectList, filterItemData.code, childItemData.value);
                } else if (childItemData.select == 2) {
                  //选中第二项
                  addValue(selectList, filterItemData.code,
                      "【asc】-${childItemData.value}");
                }
              }
            }
          }
          break;
        case filterItemTypeTime:
          {}
          break;
        default:
          break;
      }
    }
    if (isInit) {
      if (widget.onInit != null) {
        widget.onInit!(selectList);
      }
    } else {
      widget.onSelect(selectList);
    }
  }

  void addValue(
      List<FilterSelectData> selectList, String? code, String? value) {
    if (code != null && value != null) {
      for (FilterSelectData selectData in selectList) {
        if (code == selectData.code) {
          if (!selectData.values.contains(value)) {
            selectData.values.add(value);
          }
          return;
        }
      }
      //添加value
      selectList.add(FilterSelectData(code, [value]));
    }
  }
}
